<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <FormPanel ref="formPanel" :list="formList" :cols="1" labelWidth="115" @formChange="formChangeHandle":isSubmitBtn="false" style="margin-left: 20px;margin-right: 50px;"/>
      <div style="padding-top: 1rem;"></div>
      <div :style="{
          position: 'absolute',
          left: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }">
        <multiuse-button v-if="this.type !== 'detail'" type="detail" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </Spin>
  </div>
</template>
<script>
import { notifyAction } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import { getCarSeries } from '@/api/claim/factory/GenerallyCarPartTypeWarrantyMaintain';
import { stationLevel,saveOne,updateByPtId } from '@/api/claim/factory/LaborHourPrice';
import { doubleCheck ,number} from '@/utils/validate';
import moment from "moment";
export default {
  mixins: [dictionary],
  components: {},
  props: {
    rowData: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      saveData:null,
      formList: this.createFormList1(),
      loading: false,
      formData: {},
      flag : false,
      status:null
    };
  },
  mounted(){
    console.log("this.rowData",this.rowData)
    this.formChangeHandle();

  },

  methods: {
    formChangeHandle(val) {
        if (this.rowData.status===null){
          console.log("this.rowData.status",this.rowData.status)
          this.rowData.status = 2;
          console.log("this.rowData.status",this.rowData.status)
        }
      this.saveData = val;
      this.saveData = this.rowData
    },
    numberFormat(input) {
      if (!isNaN(Number(input))) {
        input = Number(input).toFixed(2);
      }
      input = this.formatNumber(input);
      return input
    },
    // 数字格式化
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },
    async chuqi() {
      if(this.type === "edit"){
        this.formList.forEach(x => {
          x.initialValue = this.formData[x.fieldName];
          if(x.fieldName === 'seriesCode'){
            x.disabled = true;
            x.itemList = [{ text: this.formData.seriesName,value: this.formData.seriesCode }];
          }
          if(x.fieldName === 'result'){
            x.disabled = true;
            x.itemList = [{ text: this.formData.dealerLevelName,value: this.formData.dealerLevel }];
          }
        });
      }
      if(this.type === "add"){
        const res = await getCarSeries();
        if (res.resultCode == 200) {
          this.formList.find(x => x.fieldName == 'seriesCode').itemList = res.data.map(x => ({ text: x.seriesName, value: x.SERIES_CODE }));
        }
        const result = await stationLevel();
          if (result.resultCode == 200) {
            this.formList.find(x => x.fieldName == 'dealerLevel').itemList = result.data.map(x => ({ text: x.dealerLevelName, value: x.dealerLevel }));
        }
      }
      if(this.type === 'detail'){
        this.formList.forEach(x => {
          x.initialValue = this.formData[x.fieldName];
          x.disabled = true;
          if(x.fieldName === 'seriesCode'){
            x.disabled = true;
            x.itemList = [{ text: this.formData.seriesName,value: this.formData.seriesCode }];
          }
          if(x.fieldName === 'dealerLevel'){
            x.itemList = [{ text: this.formData.dealerLevelName,value: this.formData.dealerLevel }];
          }
        });
      }
    },
    async saveDialog() {
      let res = null;
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      console.log('data', data);
      console.log('rowData', this.rowData);
      console.log('err', err);
      if (err) return;
        this.loading = true;

      res = await updateByPtId({...data});
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          notifyAction('保存成功！');
          this.closeDialog();
        }
      }else{
        this.loading = false;
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', false);
    },
    createFormList1() {
      return [
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelCode',
          readonly: true, // 只读
          disabled: true, //置灰
          initialValue: this.rowData.modelCode,
          placeholder: '请选择...',
        },
        {
          type: 'INPUT',
          label: '服务站代码',
          fieldName: 'ownerCode',
          readonly: true, // 只读
          disabled: true, //置灰
          placeholder: '请选择...',
          initialValue: this.rowData.ownerCode,
        },
        {
          type: 'INPUT',
          label: '服务站名称',
          readonly: true, // 只读
          disabled: true, //置灰
          fieldName: 'ownerName',
          initialValue: this.rowData.ownerName,
        },
        {
          type: 'INPUT',
          label: '索赔基数',
          fieldName: 'base',
          initialValue: this.rowData.base,
          change:value =>  {
            console.log(value)
            this.formList.find(x => x.fieldName === 'labourPricePlan').initialValue  = (this.createDictText(this.formList.find(x => x.fieldName === 'modulus').initialValue, "5520") * value).toFixed(2)
          },
          rules: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback(new Error('请输入索赔基数...'));
                }
                if (!Number.isInteger(Number(value))) {
                  return callback(new Error('请输入整数...'));
                }
                if(value.length > 30){
                  return callback(new Error('请输入30位以内的数值'));
                }
                callback();
              },
              trigger: ['blur', 'change'],
            },
          ],
        },
        {
          type: 'SELECT',
          label: '考评系数',
          fieldName: 'modulus',
          dataIndex:'modulus',
          initialValue: this.rowData['modulus'],
          rules: [{required: true, message: '请选择考评系数...', trigger: 'blur'}],
          itemList: this.createDictList('5520'),
          change:value =>  {
            let modulus = this.createDictText(value, "5520")
            let base = this.formList.find(x => x.fieldName === 'base').initialValue;
            this.formList.find(x => x.fieldName === 'labourPricePlan').initialValue  = (modulus * base).toFixed(2)

          },
        },
        {
          type: 'INPUT_NUMBER',
          label: '计划索赔工时单价',
          fieldName: 'labourPricePlan',
          initialValue: (this.createDictText(this.rowData.modulus, "5520") * this.rowData.base).toFixed(2),
          readonly: true, // 只读
          number:true,
          disabled: true, //置灰
          rules: [{required: true, message: '请选择考评系数...', trigger: 'blur'}],
        },
        {
          type: 'SELECT',
          label: '服务考评结果',
          fieldName: 'result',
          dataIndex:'result',
          initialValue: this.rowData['result'],
          rules: [{required: true, message: '选择服务考评结果...', trigger: 'blur'}],
          itemList: this.createDictList('5519'),
        },
        {
          type: 'DATE',
          label: '生效日期',
          fieldName: 'validDate',
          placeholder: '请选择',
          dateType: 'exactdate',
          minDateTime: moment().add(-1, 'days'),
          initialValue: this.rowData['validDate'],
          rules: [{ required: true, message: '请选择申请日期', trigger: 'change' }]
        },
      ];

    }
  },
  created() {
    this.chuqi();

  }
};
</script>

<style lang="less" scoped></style>
